package cn.xyy.system.service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.xyy.system.dao.UserDao;
import cn.xyy.common.domain.system.auth.UserInfo;
import cn.xyy.common.domain.system.auth.UserInfoVO;
import cn.xyy.common.domain.system.auth.UserRole;
import cn.xyy.common.utils.BeanUtils;
import cn.xyy.common.utils.MD5Utils;
import cn.xyy.common.utils.StringUtils;
import cn.xyy.common.utils.UUIDUtils;
import cn.xyy.common.exception.AuthException;
import cn.xyy.common.domain.mvc.Page;

/**
 * 用户业务层
 * 
 * @author xyy
 *
 */
@Service
public class UserService {
	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleService roleService;

	public Page<UserInfo> getUserListPage(UserInfoVO user) {
		if (user == null) {
			throw new AuthException("参数不能为空");
		}
		Page<UserInfo> page = userDao.selectPage(user);
		if (page.getItems() != null && !page.getItems().isEmpty()) {
			page.getItems().stream().forEach(e -> {
				e.setRoleList(roleService.getRoleListByUser(e.getUid()));
			});
		}
		return page;
	}

	public UserInfo getUser(String uid) {
		if (StringUtils.isBlank(uid)) {
			throw new AuthException("参数不能为空");
		}
		return userDao.selectById(uid, UserInfo.class);
	}

	@Transactional(value = "baseTransactionManager")
	public boolean add(UserInfoVO vo) throws AuthException {

		if (StringUtils.isBlank(vo.getRealName())) {
			throw new AuthException("真实姓名不能为空");
		}
		if (StringUtils.isBlank(vo.getUsername())) {
			throw new AuthException("登陆名不能为空");
		}
		if (StringUtils.isBlank(vo.getPassword())) {
			throw new AuthException("登陆密码不能为空");
		}
		if (vo.getDeptId() == null) {
			throw new AuthException("请选择部门");
		}

		UserInfo existUser = userDao.select(new UserInfo().setUsername(vo.getUsername()));
		if (existUser != null) {
			throw new AuthException("账号已存在");
		}

		UserInfo user = new UserInfo();
		BeanUtils.copyProperties(vo, user);
		user.setCreateTime(new Date());
		String password = MD5Utils.getMD5Encoding(user.getPassword());
		user.setPassword(password);
		user.setUid(UUIDUtils.generateUUID());
		// 保存用户信息
		int result = userDao.insert(user);
		if (result < 0) {
			throw new AuthException("保存失败");
		}

		if (vo.getRoleIdList() != null && vo.getRoleIdList().length > 0) {

			List<UserRole> urList = Arrays.stream(vo.getRoleIdList()).map(e -> {
				UserRole ur = new UserRole();
				ur.setUserId(user.getUid());
				ur.setRoleId(e);
				return ur;
			}).collect(Collectors.toList());

			// 保存用户分配的角色
			saveRelationRole(urList);
		}
		return true;
	}

	public boolean update(UserInfoVO vo) {

		if (vo.getUid() == null) {
			throw new AuthException("用户不存在");
		}
		if (vo.getDeptId() == null) {
			throw new AuthException("请选择部门");
		}
		UserInfo user = userDao.selectOne(vo.getUid());
		if (user == null) {
			throw new AuthException("用户不存在");
		}
		String password = "";
		if (!user.getPassword().equals(vo.getPassword())) {
			password = MD5Utils.getMD5Encoding(vo.getPassword());
		}
		BeanUtils.copyProperties(vo, user);
		if (StringUtils.isNotBlank(password)) {
			user.setPassword(password);
		}
		int result = userDao.update(user);
		if (result < 0) {
			throw new AuthException("修改失败");
		}

		// 删除用户角色
		userDao.delete(new UserRole().setUserId(user.getUid()));

		if (vo.getRoleIdList() != null && vo.getRoleIdList().length > 0) {
			List<UserRole> urList = Arrays.stream(vo.getRoleIdList()).map(item -> {
				UserRole ur = new UserRole();
				ur.setUserId(user.getUid());
				ur.setRoleId(item);
				return ur;
			}).collect(Collectors.toList());
			// 保存用户分配的角色
			saveRelationRole(urList);
		}
		return true;

	}

	public boolean saveRelationRole(List<UserRole> urList) {
		userDao.insert(urList);
		return true;
	}

	public boolean delete(String uid) throws AuthException {
		if (StringUtils.isBlank(uid)) {
			throw new AuthException("uid不能为空");
		}
		int result = userDao.delete(new UserInfo().setUid(uid));
		if (result < 0) {
			throw new AuthException("删除失败");
		}
		return true;
	}

	/**
	 * 更新用户状态
	 */

	public boolean updateState(UserInfoVO vo) {
		if (StringUtils.isBlank(vo.getUid())) {
			throw new AuthException("uid不能为空");
		}
		int result = userDao.updateState(vo.getUid(), vo.getStatus());
		if (result < 0) {
			throw new AuthException("更新失败");
		}
		return true;
	}

}
